<?php
/**

 * 支付宝支付

 * @author maniac

 */

namespace app\common\service;


use app\facade\Wechat as WechatFacade;
use think\facade\Env;
use think\facade\Log As Log;
use app\facade\Orders;


require_once Env::get("extend_path")."/alipay/AopSdk.php";
class Alipay extends Base

{

	private $appId = '2021001151680680';
	private $rsaPrivateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCEJr49KaCiSwCmtW45SeeQ4SryLTGmuDMz+2iij9iZwoCDxj4Q6KwDkGgSFZo8q8zxj6pbm7yzNSuAX5BiCTtmqgO5vpEpbk6XW1im4HOqg/dV49mIHc//P7TXVNC+Wr1BNwTTxTFbz8Q8hyQsAY6ISp1cV5Wj/XP3o0OZJ+1sIQFQ+4HWGDEjqP7jFzzp4Vj0eVYmMm9thSq8FrcZKMDeq345aNoTLhdrooN+3f5Gj7Evs9FT+vjXz4NAUEaUQkRk6FQ/I8ztsbR589xAcYUhXaPSD895QiyGD2cwrGmjm5ClNRxuklwtBv88TBWMJtfqYuQUpfwttN4D1WR/Oq5BAgMBAAECggEAWFzDhYgJFZuLAu17lyjYgqJcofQgJ/cwnYh0jYYbcayBXBs5Mvsw0W1EeRsit4C0l6zVX03CHh3mSX8cvsCnjF0QAqnuzEIqoL/+hg68qH526mJg+MfeZTEGzZizvyRTOYD9ZFCNUXOaJlLCl/4ufOlPUQhrUWzOlv3+3DC7azmg/SR72ayzVeJhg3rJ7da0++J7MCX/44Rj2ZwyLc2kBElMZ1xrcyfqJ+xETMYIMpv8q25NWGKQoGGXuL5k4PeXVjXxscB8HVxy314TVelfxxbHbTr7iU59fFFscFgEJUb2fCyOYoalFv/eXPwiC2/qka6IAOlnPMEK+W3V3vPb8QKBgQD5aEWvEsQPuLtyz6M7LZ5rk0QOQfKyXOf8eHkhxS0WnB85qHa32qgcgJBPhebH6Ffj/xHGappAoEwvvG+ad5zzI2WO6/uZkcjALbk9hFIvliylBDqXl6dkwpr54vijd94/6JaJoQ2WGTyH62tuunRWrFK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J+4H1ViigJ7lbXND1SWpJRlTjZMNvh6qMZ6IHQIDAQAB';
	private $pid = '2088831027536250';
	
    public function requestPay($data){
//        require_once EXTEND_PATH."alipay/AopSdk.php";
        $c = new \AopClient;
        $c->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $c->appId = $this->appId;
        $c->rsaPrivateKey = $this->rsaPrivateKey;
        $c->format = "json";
        $c->charset= "UTF-8";
        $c->signType= "RSA2";
        $c->alipayrsaPublicKey = $this->alipayrsaPublicKey;
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.open.public.template.message.industry.modify
        //$request = new \AlipayOpenPublicTemplateMessageIndustryModifyRequest();
        $request=new \AlipayTradeAppPayRequest();
        $bizcontent = "{\"body\":\"我是测试数据\","
            . "\"subject\": \"App支付测试\","
            . "\"out_trade_no\": \"".$data['out_trade_no']."\","
            . "\"timeout_express\": \"30m\","
            . "\"total_amount\": \"0.01\","
            . "\"product_code\":\"QUICK_MSECURITY_PAY\""
            . "}";
        $request->setNotifyUrl(config('site.app_uri')."api/v1/notify");
        $request->setBizContent($bizcontent);
//这里和普通的接口调用不同，使用的是sdkExecute
        
        $response = $c->sdkExecute($request);
//htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
        //Log::write($response,'notice');
        return $response;

        //return htmlspecialchars($response);//就是orderString 可以直接给客户端请求，无需再做处理。

    }


    public function notify($data){

        $c = new \AopClient;
        $c->alipayrsaPublicKey = $this->alipayrsaPublicKey;

        $flag = $c->rsaCheckV1($data, NULL, "RSA2");

        file_put_contents("anotifypay.txt",json_encode($data)."\r\n",FILE_APPEND);
        if ($flag) {
            $data["transaction_id"]=$data["trade_no"];
            $data["pay_type"]=2;
            WechatFacade::notify($data);
            echo "success";
        }else{
            file_put_contents('paylog/alipay/'.date("Y-m-d").'.txt', date("Y-m-d H:i:s")."失败\r\n".json_encode($data)."\r\n",FILE_APPEND);

            echo "fail";
        }
        return ;
    }

    public function getUser($code){
    	
    	require_once EXTEND_PATH."alipay/AopSdk.php";
    	
    	//获取access_token
    	$aop = new \AopClient;
    	$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
    	$aop->appId = $this->appId;
    	$aop->rsaPrivateKey = $this->rsaPrivateKey;
    	$aop->format = 'json';
    	$aop->charset = 'UTF-8';
    	$aop->signType = 'RSA2';
    	$aop->alipayrsaPublicKey = $this->alipayrsaPublicKey;
    	$aop->apiVersion = '1.0';
    	$request = new \AlipaySystemOauthTokenRequest();
    	$request->setGrantType("authorization_code");
    	$request->setCode($code);
    	
    	$result = $aop->execute($request);
    	$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
    	$resultData = (array) $result->$responseNode;
    	if (empty($resultData['access_token'])) {
    		exception('获取access_token失败');
    	}
    	//获取用户信息
    	$request = new \AlipayUserInfoShareRequest ();
    	$result = $aop->execute ( $request , $resultData['access_token'] );
    	$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
    	$userData = (array) $result->$responseNode;
    	if (empty($userData['code']) || $userData['code'] != 10000) {
    		exception('获取用户信息失败');
    	}
    	return $userData;
    }
  
    public function alipay_login()
    
    {
    	
    	require_once EXTEND_PATH."alipay/AopSdk.php";
    	$c = new \AopClient;
    	$c->gatewayUrl = "https://openapi.alipay.com/gateway.do";
    	$c->appId = $this->appId;
    	$c->rsaPrivateKey = $this->rsaPrivateKey;
    	$c->format = "json";
    	$c->charset= "UTF-8";
    	$c->signType= "RSA2";
    	$c->alipayrsaPublicKey = $this->alipayrsaPublicKey;
    	$data['apiname'] = 'com.alipay.account.auth';
    	$data['app_id'] = $this->appId;
    	$data['app_name'] = 'mc';
    	$data['auth_type'] = 'AUTHACCOUNT';
    	$data['biz_type'] = 'openservice';
    	$data['method'] = 'alipay.open.auth.sdk.code.get';
    	$data['pid'] = $this->pid;
    	$data['product_id'] = 'APP_FAST_LOGIN';
    	$data['scope'] = 'kuaijie';
    	$data['sign_type'] = 'RSA2';
    	$data['target_id'] = unid();
    	$result = $c->rsaSign($data, 'RSA2');
    	$data['sign'] = $result;
    	
    	$result = $c->getSignContentUrlencode($data);
    	return $result;
    }
}


